from datetime import datetime
from app import db

class StatusUpdate(db.Model):
    __tablename__ = 'status_updates'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    work_status = db.Column(db.String(20), nullable=False)  # on_site, remote, leave, out
    location = db.Column(db.String(200))
    current_task = db.Column(db.Text)
    objective_id = db.Column(db.Integer, db.ForeignKey('objectives.id'), nullable=True)  # 关联的目标
    notes = db.Column(db.Text)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    # 关系
    objective = db.relationship('Objective', foreign_keys=[objective_id])

    def to_dict(self):
        return {
            'id': self.id,
            'user_id': self.user_id,
            'user_name': self.user.full_name if self.user else None,
            'work_status': self.work_status,
            'location': self.location,
            'current_task': self.current_task,
            'objective_id': self.objective_id,
            'objective_title': self.objective.title if self.objective else None,
            'notes': self.notes,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }


class ProgressUpdate(db.Model):
    __tablename__ = 'progress_updates'

    id = db.Column(db.Integer, primary_key=True)
    objective_id = db.Column(db.Integer, db.ForeignKey('objectives.id'), nullable=True)
    key_result_id = db.Column(db.Integer, db.ForeignKey('key_results.id'), nullable=True)
    project_id = db.Column(db.Integer, db.ForeignKey('projects.id'), nullable=True)
    previous_value = db.Column(db.Float)
    new_value = db.Column(db.Float)
    notes = db.Column(db.Text)
    updated_by = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    # 关系
    updater = db.relationship('User', foreign_keys=[updated_by])

    def to_dict(self):
        return {
            'id': self.id,
            'objective_id': self.objective_id,
            'key_result_id': self.key_result_id,
            'project_id': self.project_id,
            'previous_value': self.previous_value,
            'new_value': self.new_value,
            'notes': self.notes,
            'updated_by': self.updated_by,
            'updater_name': self.updater.full_name if self.updater else None,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }